<template>
  <div style="height: 100%">
    <div class="searchList">
      <div class="row">
        <field
          class="leftField"
          right-icon="arrow-down"
          readonly
          clickable
          name="picker"
          :value="searchForm.building"
          label-width="30px"
          label="区域"
          placeholder="选择区域"
          @click="showPickerBuilding = true"
        ></field>
        <popup v-model="showPickerBuilding" position="bottom">
          <picker
            show-toolbar
            :columns="columnsBuilding"
            @confirm="onConfirmBuilding"
            @cancel="showPickerBuilding = false"
          />
        </popup>
        <field
          class="rightField equipType"
          v-model="equipmentNumber"
          label-width="60px"
          label="设备编号"
          placeholder="请输入编号"
          @blur="inputNumChange"
        />
      </div>
      <div class="row">
        <field
          class="leftField"
          right-icon="arrow-down"
          readonly
          clickable
          name="picker"
          :value="equipmentType"
          label-width="30px"
          label="类型"
          placeholder="选择类型"
          @click="showPickerType = true"
        />
        <popup v-model="showPickerType" position="bottom">
          <picker
            show-toolbar
            value-key="equipmentTypeName"
            :columns="columnsType"
            @confirm="onConfirmType"
            @cancel="showPickerType = false"
          />
        </popup>
        <field
          class="rightField"
          :right-icon="searchForm.startTime ? 'close' : 'underway-o'"
          label-width="60px"
          readonly
          clickable
          name="datetimePicker"
          :value="searchForm.startTime"
          label="开始时间"
          placeholder="选择时间"
          @click="e => eventClick(e, 'startTime')"
        />
        <popup v-model="showPickerStartTime" position="bottom">
          <datetime-picker
            type="date"
            title="选择年月日"
            :value="
              searchForm.startTime
                ? new Date(
                    searchForm.startTime.split('-')[0],
                    searchForm.startTime.split('-')[1] - 1,
                    searchForm.startTime.split('-')[2]
                  )
                : new Date()
            "
            @confirm="onConfirmStartTime"
            @cancel="showPickerStartTime = false"
          />
        </popup>
      </div>
      <div class="row">
        <field
          class="leftField"
          right-icon="arrow-down"
          readonly
          clickable
          name="picker"
          :value="searchForm.floor"
          label-width="30px"
          label="楼层"
          placeholder="选择楼层"
          @click="showPickerFloor = true"
        />
        <popup v-model="showPickerFloor" position="bottom">
          <picker
            show-toolbar
            :columns="columnsFloor"
            @confirm="onConfirmFloor"
            @cancel="showPickerFloor = false"
          />
        </popup>
        <!-- clear underway-o -->
        <field
          class="rightField"
          :right-icon="searchForm.endTime ? 'close' : 'underway-o'"
          label-width="60px"
          readonly
          clickable
          name="datetimePicker"
          :value="searchForm.endTime"
          label="结束时间"
          placeholder="选择时间"
          @click="e => eventClick(e, 'endTime')"
        />
        <popup v-model="showPickerEndTime" position="bottom">
          <datetime-picker
            type="date"
            :value="
              searchForm.endTime
                ? new Date(
                    searchForm.endTime.split('-')[0],
                    searchForm.endTime.split('-')[1] - 1,
                    searchForm.endTime.split('-')[2]
                  )
                : new Date()
            "
            title="选择年月日"
            @confirm="onConfirmEndTime"
            @cancel="showPickerEndTime = false"
          />
        </popup>
      </div>
    </div>
    <div class="tabNav">
      <tabs v-model="active">
        <tab title="全部" name="全部">
          <div class="listAll a">
            <alarm-list
              :change-search="changeSearch1"
              @getList="getListAll"
              @changeSearchBack="changeSearchBack1"
            ></alarm-list>
          </div>
        </tab>
        <tab title="未办" name="未办">
          <div class="listAll b">
            <alarm-list
              :change-search="changeSearch2"
              @getList="getListOff"
              @changeSearchBack="changeSearchBack2"
            ></alarm-list>
          </div>
        </tab>
        <tab title="已办" name="已办">
          <div class="listAll c">
            <!-- <alarm-list
              :change-search="changeSearch3"
              @getList="getListOn"
              @changeSearchBack="changeSearchBack3"
            ></alarm-list> -->
            <div class="noMore">
              没有更多了
            </div>
          </div>
        </tab>
        <tab title="我处置的" name="我处置的">
          <div class="listAll d">
            <!-- <alarm-list
              :change-search="changeSearch4"
              @getList="getListMe"
              @changeSearchBack="changeSearchBack4"
            ></alarm-list> -->
            <div class="noMore">
              没有更多了
            </div>
          </div>
        </tab>
      </tabs>
    </div>
  </div>
</template>

<script>
import { Field, Popup, Picker, DatetimePicker, Tab, Tabs, Toast } from "vant";
import { alarmInfoList, equipmentTypeList, getFloorsList } from "@/api/Alarm";
import AlarmList from "./components/AlarmList";
export default {
  name: "overview",
  components: {
    Field,
    Popup,
    Picker,
    DatetimePicker,
    Tab,
    Tabs,
    AlarmList
  },
  data() {
    return {
      isBackFromDeatail: false,
      maxStartDate: new Date(),
      changeSearch1: false,
      changeSearch2: false,
      changeSearch3: false,
      changeSearch4: false,
      userInfo: {},
      columnsBuilding: ["全部"],
      buildingFromApi: [],
      columnsType: ["烟感", "温感"],
      columnsFloor: ["全部"],
      floorFromApi: [],
      showPickerBuilding: false,
      showPickerType: false,
      showPickerFloor: false,
      showPickerStartTime: false,
      showPickerEndTime: false,
      equipmentType: "全部",
      equipmentNumber: "",
      searchForm: {
        building: "全部",
        equipmentNumber: "",
        equipmentType: "",
        startTime: "",
        endTime: "",
        floor: "全部"
      },
      active: "全部"
      // 下面部分
    };
  },
  watch: {
    searchForm: {
      handler(v) {
        this.changeSearch1 = true;
        this.changeSearch2 = true;
        this.changeSearch3 = true;
        this.changeSearch4 = true;
      },
      deep: true
    }
  },
  async mounted() {
    await this.getFloors()
    await this.equipmentTypeList()
    const currentRoute = this.$route
    // this.userInfo = JSON.parse(sessionStorage.getItem("pcUserInfo"));
    // 如果是从详情页条状过来，保留查询条件
    if (currentRoute.query.from === "/alaem/detail") {
      this.isBackFromDeatail = true
      let lastQueryParams = JSON.parse(sessionStorage.getItem('queryParams'))
      this.searchForm.building = this.searchForm.building === undefined ? "全部" : lastQueryParams.building
      this.searchForm.floor = this.searchForm.floor === undefined ? "全部"  : lastQueryParams.floor
      this.searchForm.equipmentNumber = lastQueryParams.equipmentNumber
      this.equipmentNumber = lastQueryParams.equipmentNumber
      this.searchForm.equipmentType = lastQueryParams.equipmentType
      this.equipmentType = lastQueryParams.equipmentType
      this.searchForm.startTime = lastQueryParams.reportTimeFrom.substring(0, 10)
      this.searchForm.endTime = lastQueryParams.reportTimeTo.substring(0, 10)
      await this.onConfirmBuilding(lastQueryParams.building)
    } else {
      this.isBackFromDeatail = false
    }
    this.userInfo = {
      tenantNo: "SSIdb5cdda5114a6a62d",
      account: "auansdf"
    };
  },
  methods: {
    async getFloors() {
      let res = await getFloorsList({parentId: 0, tag: 1})
      if (res.code === 0) {
        this.buildingFromApi = res.data
        res.data.map((item, i) => {
          this.columnsBuilding.push(item.name)
        })
      }
    },
    eventClick(e, name) {
      if (e.target._prevClass.includes("van-icon-close")) {
        this.searchForm[name] = "";
        return;
      }
      if (name === "startTime") {
        this.showPickerStartTime = true;
        return;
      }
      this.showPickerEndTime = true;
    },
    changeSearchBack1(v) {
      this.changeSearch1 = v;
    },
    changeSearchBack2(v) {
      this.changeSearch2 = v;
    },
    changeSearchBack3(v) {
      this.changeSearch3 = v;
    },
    changeSearchBack4(v) {
      this.changeSearch4 = v;
    },
    inputNumChange() {
      this.searchForm.equipmentNumber = this.equipmentNumber;
    },
    async alarmInfoList(pageInfo, status, processUser) {
      let queryParams = {
        building:
          this.searchForm.building === "全部"
            ? undefined
            : this.searchForm.building,
        floor:
          this.searchForm.floor === "全部" ? undefined : this.searchForm.floor,
        equipmentNumber: this.searchForm.equipmentNumber,
        equipmentType: this.searchForm.equipmentType,
        reportTimeFrom: this.searchForm.startTime
          ? this.searchForm.startTime + " 00:00:00"
          : undefined,
        reportTimeTo: this.searchForm.endTime
          ? this.searchForm.endTime + " 23:59:59"
          : undefined,
        // processUser: processUser,
        processState: status,
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        // tenantNo: this.userInfo.tenantNo // "SSIdb5cdda5114a6a62d"
      }
      sessionStorage.setItem('queryParams', JSON.stringify(queryParams))

      // 请选择开始时间和结束时间！
      let res = await alarmInfoList(queryParams);
      if (res.code === 0) {
        // this.columnsFloor = ["全部"].concat(res.data.floors);
        // this.columnsBuilding = ["全部"].concat(res.data.buildings);
        return res.data.records; //.result.pageResult;
      }
    },
    async equipmentTypeList() {
      let res = await equipmentTypeList();
      if (res.code === 0) {
        this.columnsType = [
          { equipmentTypeId: "", equipmentTypeName: "全部" }
        ].concat(res.data); //(res.result)
      }
    },
    async onConfirmBuilding(value) {
      this.searchForm.building = value;
      this.showPickerBuilding = false;
      let choseObj = {}
      this.columnsFloor = ['全部']
      if (!this.isBackFromDeatail) this.searchForm.floor = "全部"
      this.buildingFromApi.map((item, i) => {
        if (value === item.name) {
          choseObj = item
        }
      })
      if (choseObj.id !== undefined) {
        let res = await getFloorsList({parentId: choseObj.id, tag: 2})
        if (res.code === 0) {
          res.data.map((item, i) => {
            this.columnsFloor.push(item.name)
          })
        }
      }
    },
    onConfirmType(value) {
      this.equipmentType = value.equipmentTypeName;
      this.searchForm.equipmentType = value.equipmentTypeName; // value.equipmentTypeId;
      this.showPickerType = false;
    },
    onConfirmFloor(value) {
      this.searchForm.floor = value;
      this.showPickerFloor = false;
    },
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(),
        "m+": (date.getMonth() + 1).toString(),
        "d+": date.getDate().toString(),
        "H+": date.getHours().toString(),
        "M+": date.getMinutes().toString(),
        "S+": date.getSeconds().toString()
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
          );
        }
      }
      return fmt;
    },
    onConfirmStartTime(value) {
      this.searchForm.startTime = this.dateFormat("YYYY-mm-dd", value);
      this.showPickerStartTime = false;
    },
    onConfirmEndTime(value) {
      this.searchForm.endTime = this.dateFormat("YYYY-mm-dd", value);
      this.showPickerEndTime = false;
    },
    getListAll(pageInfo, callback) {
      let bool =
        (!!this.searchForm.startTime && !!this.searchForm.endTime) ||
        (!this.searchForm.startTime && !this.searchForm.endTime);
      if (!bool) {
        Toast.fail("请选择开始时间和结束时间！");
        return;
      }
      this.alarmInfoList(pageInfo, undefined).then(res => {
        callback(res);
      });
    },
    getListOff(pageInfo, callback) {
      let bool =
        (!!this.searchForm.startTime && !!this.searchForm.endTime) ||
        (!this.searchForm.startTime && !this.searchForm.endTime);
      if (!bool) {
        Toast.fail("请选择开始时间和结束时间！");
        return;
      }
      this.alarmInfoList(pageInfo, 0, undefined).then(res => {
        callback(res);
      });
    },
    getListOn(pageInfo, callback) {
      this.alarmInfoList(pageInfo, 2, undefined).then(res => {
        callback(res);
      });
    },
    getListMe(pageInfo, callback) {
      this.alarmInfoList(pageInfo, 2, this.userInfo.account).then(res => {
        callback(res);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.searchList {
  width: 100%;
  .row {
    display: flex;
  }
  .equipType {
    padding: 10px 10px 10px 0 !important;
    /deep/ .van-field__control {
      border-radius: 5px !important;
    }
  }
  /*height: 150px;*/
  .van-cell {
    position: unset;
    border: none;
    background: transparent;
    /deep/ .van-field__label {
      color: white;
    }
    /deep/ .van-field__control {
      background-color: white;
      color: #666666;
      border-radius: 5px 0 0 5px;
      box-sizing: border-box;
      padding-left: 10px;
    }
  }
  .rightField {
    padding: 10px 18px 10px 0;
    width: 55%;
  }
  .leftField {
    padding-left: 10px;
    width: 45%;
  }
}
/deep/ .van-field__right-icon {
  background: white !important;
  padding: 0 4px 0 0;
  border-radius: 0 5px 5px 0;
  color: #fc5a69;
}
.tabNav {
  padding: 0 5%;
  box-sizing: border-box;
  height: calc(100% - 135px);
  .van-tabs {
    height: 100%;
  }
  /deep/ .van-tabs__wrap {
    width: 100%;
    border-radius: 5px;
    box-shadow: 0px 1px 2px 0px #cccccc;
  }
  /deep/ .van-tabs__content {
    width: 100%;
    height: calc(100% - 50px);
    margin-top: 5px;
    .van-tab__pane,
    .van-tab__pane-wrapper {
      height: 100%;
      .listAll {
        height: 100%;
        overflow: scroll;
      }
    }
  }
  /deep/ .van-tabs__line {
    background-color: #fc5a69;
  }
}
.noMore {
  text-align: center;
  line-height: 50px;
  color: #9e9b9b;
  font-size: 20;
}
</style>
